package com.ruoyi.web.controller.system;

import java.util.List;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.web.controller.tool.Statics;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.shiro.service.SysPasswordService;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.service.ISysPostService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;

/**
 * 用户信息
 *
 * @author ruoyi
 * 0e59942f-8d2c-4cba-9026-139b3174149a
 */
@Controller
@RequestMapping("/system/user")
public class SysUserController extends BaseController {
    private String prefix = "system/user";

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private ISysDeptService deptService;



//9c4f9c08-3425-484d-b0ce-bfcf833d1db7
    @RequiresPermissions("system:user:view")
    @GetMapping()
    public String user() {
        return prefix + "/user";
    }

    @RequiresPermissions("system:user:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(SysUser user) {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    /**
     * 61ef5e3b-6ea6-4ac3-b28e-371ee8f2f9fd
     * XiaoYi...system/user/adds/list
     * 通过医院、角色查询 用户列表
     *
     * @Date : 2020-03-18 08:51
     */
    @RequiresPermissions("system:user:list")
    @PostMapping("/adds/list")
    @ResponseBody
    public TableDataInfo getUserList(@RequestParam("stagingId") String stagingId) {
        return getDataTable(userService.getHealthWorker(stagingId));
    }

    /**
     *
     * <p/>
     *
     * <p/>
     *
      * @param	user
     * @return com.ruoyi.common.core.domain.AjaxResult
     *
     * @throws
     * @author  XiaoYi...
     * @date    2021/1/28 4:42 下午
     * a8389b84-da88-447d-9c64-8b2ce645c3cf
     */
    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @RequiresPermissions("system:user:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(SysUser user) {
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        return util.exportExcel(list, "用户数据");
    }

    /**
     *
     * <p/>
     *
     * <p/>
     *
      * @param	file
     * @param	updateSupport
     * @return com.ruoyi.common.core.domain.AjaxResult
     *
     * @throws
     * @author  XiaoYi...
     * @date    2021/1/28 4:42 下午
     * 7f7fa943-1559-4147-a0d1-8181a18075ff
     */
    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @RequiresPermissions("system:user:import")
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        String operName = ShiroUtils.getSysUser().getLoginName();
        String message = userService.importUser(userList, updateSupport, operName);
        return AjaxResult.success(message);
    }
/**
 *
 * <p/>
 *
 * <p/>
 *
  * @param
 * @return com.ruoyi.common.core.domain.AjaxResult
 *
 * @throws
 * @author  XiaoYi...
 * @date    2021/1/28 4:42 下午
 * 9adbf842-a93a-4bc4-8009-399878a419ea
 */
    @RequiresPermissions("system:user:view")
    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate() {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        return util.importTemplateExcel("用户数据");
    }

    /**
     * c140ba17-1cd2-4715-a8f2-86f563fa317d
     * 新增用户
     */
    @GetMapping("/add")
    public String add(ModelMap mmap) {

        mmap.put("roles", roleService.selectRoleAll());
        mmap.put("posts", postService.selectPostAll());
        mmap.put("dept", deptService.selectDeptById(ShiroUtils.getSysUser().getDeptId()));
        return prefix + "/add";
    }

    /**
     * e88564af-f08b-43bd-8ca1-311fdd44a0e0
     * 新增保存用户
     */
    @RequiresPermissions("system:user:add")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@Validated SysUser user) {
        // 密码验证
        if(StringUtils.isEmpty(user.getPassword())){
            return error("密码不能为空");
        }
        if( !user.getPassword().matches(Statics.regex1) ){
            return error("密码必须包含大写字母、小写字母、数字、特殊符号，且在8到20位之间");
        }
        if (UserConstants.USER_NAME_NOT_UNIQUE.equals(userService.checkLoginNameUnique(user.getLoginName()))) {
            return error("新增用户'" + user.getLoginName() + "'失败，登录账号已存在");
        }
//        else if (UserConstants.USER_PHONE_NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
//            return error("新增用户'" + user.getLoginName() + "'失败，手机号码已存在");
//        } else if (UserConstants.USER_EMAIL_NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
//            return error("新增用户'" + user.getLoginName() + "'失败，邮箱账号已存在");
//        }
        user.setSalt(ShiroUtils.randomSalt());
        user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
        user.setCreateBy(ShiroUtils.getLoginName());
        return toAjax(userService.insertUser(user));
    }

    /**
     * 6ba61ecf-d83c-4769-8933-8af2d387d9e1
     * 修改用户
     */
    @GetMapping("/edit/{userId}")
    public String edit(@PathVariable("userId") Long userId, ModelMap mmap) {
        mmap.put("user", userService.selectUserById(userId));
        mmap.put("roles", roleService.selectRolesByUserId(userId));
//        mmap.put("loginType", );//
        mmap.put("posts", postService.selectPostsByUserId(userId));
        return prefix + "/edit";
    }

    /**
     * 272f4d52-b541-4d78-98bc-21f0df09a868
     * 修改保存用户
     */
    @RequiresPermissions("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@Validated SysUser user) {
        userService.checkUserAllowed(user);
//        if (UserConstants.USER_PHONE_NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
//            return error("修改用户'" + user.getLoginName() + "'失败，手机号码已存在");
//        } else if (UserConstants.USER_EMAIL_NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
//            return error("修改用户'" + user.getLoginName() + "'失败，邮箱账号已存在");
//        }
        user.setUpdateBy(ShiroUtils.getLoginName());
        return toAjax(userService.updateUser(user));
    }

    /**
     * @param	userId
     * @param	mmap
     * @author  XiaoYi...
     * @date    2021/1/28 4:42 下午
     * 8bd7d88b-f7f4-4820-866b-19d63503a112
     */
    @RequiresPermissions("system:user:resetPwd")
    @Log(title = "重置密码", businessType = BusinessType.UPDATE)
    @GetMapping("/resetPwd/{userId}")
    public String resetPwd(@PathVariable("userId") Long userId, ModelMap mmap) {
        mmap.put("user", userService.selectUserById(userId));
        return prefix + "/resetPwd";
    }


    //5cbeeefd-4607-4f7f-8ff3-e1ead6c555fe
    @RequiresPermissions("system:user:resetPwd")
    @Log(title = "重置密码", businessType = BusinessType.UPDATE)
    @PostMapping("/resetPwd")
    @ResponseBody
    public AjaxResult resetPwdSave(SysUser user) {
        // 密码验证
        if(StringUtils.isEmpty(user.getPassword())){
            return error("密码不能为空");
        }
        if( !user.getPassword().matches(Statics.regex1) ){
            return error("密码必须包含大写字母、小写字母、数字、特殊符号，且在8到20位之间");
        }
        userService.checkUserAllowed(user);
        user.setSalt(ShiroUtils.randomSalt());
        user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
        if (userService.resetUserPwd(user) > 0) {
            if (ShiroUtils.getUserId() == user.getUserId()) {
                ShiroUtils.setSysUser(userService.selectUserById(user.getUserId()));
            }
            return success();
        }
        return error();
    }


    //d7a749fd-04a4-4384-8948-b80673d326b4
    @RequiresPermissions("system:user:remove")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        try {
//            删除用户
            // 获取当前的用户信息
            SysUser sysUser = ShiroUtils.getSysUser();
//            检查此用户下是否有医废
            long sum = userService.selectUserTagSum(ids);
            if (sum > 0)
                return AjaxResult.error("此用户存在" + sum + "条医废记录不允许删除");
            return toAjax(userService.deleteUserByIds(ids, sysUser.getUserId()));
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    /**
     * 校验用户名
     * 44f55e25-47d4-47ef-b77d-67807a426a24
     */
    @PostMapping("/checkLoginNameUnique")
    @ResponseBody
    public String checkLoginNameUnique(SysUser user) {
        return userService.checkLoginNameUnique(user.getLoginName());
    }

    /**
     * 校验手机号码
     * fa018bed-6e01-4cb8-a1bc-1bc91b242191
     */
    @PostMapping("/checkPhoneUnique")
    @ResponseBody
    public String checkPhoneUnique(SysUser user) {
        return userService.checkPhoneUnique(user);
    }

    /**
     * 校验email邮箱
     * cd9202aa-0497-46a9-8182-66a4bd883b6c
     */
    @PostMapping("/checkEmailUnique")
    @ResponseBody
    public String checkEmailUnique(SysUser user) {
        return userService.checkEmailUnique(user);
    }

    /**
     * 用户状态修改
     * c6051adb-8a08-46cd-89c2-400f264e851a
     */
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @RequiresPermissions("system:user:edit")
    @PostMapping("/changeStatus")
    @ResponseBody
    public AjaxResult changeStatus(SysUser user) {
        userService.checkUserAllowed(user);
        return toAjax(userService.changeStatus(user));
    }
}